package com.parent.utils;

import java.lang.reflect.Field;

/**
 * @Author yan
 * @Date 2023/6/8 0008 14:28
 * @Description
 */
public class ObjectUtils {
    /**
     *
     * @param o
     * @return
     * @throws NoSuchFieldException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static boolean isNotNull(Object o) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        return !isNull(o);
    }

    /**
     *
     * @param o
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    public static boolean isNull(Object o) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> aClass = o.getClass();
        Object newInstance = aClass.newInstance();
        if (newInstance == null) {
            return true;
        }
        if (aClass.isAssignableFrom(String.class)) {
            String string = (String) newInstance;
            return "".equals(string);
        } else {
            Field[] fields = aClass.getDeclaredFields();
            if (fields == null || fields.length <= 0) {
                return true;
            }
            for (Field field : fields) {
                // 允许访问私有属性
                field.setAccessible(true);
                String name = field.getName();
                Class<?> type = field.getType();
                // type 是 String 类型
                if (type.isAssignableFrom(String.class)) {
                    Field fieldNow = aClass.getDeclaredField(name);
                    fieldNow.setAccessible(true);
                    Object value = fieldNow.get(o);// 获取属性值
                    if (value == null) {
                        return true;
                    }
                    Class<?> fieldClass = value.getClass();
                    if (fieldClass.isAssignableFrom(String.class)) {
                        String string = (String) newInstance;
                        return "".equals(string);
                    }
                }
            }
        }

        return false;
    }
}
